﻿using System;
using System.CodeDom.Compiler;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;
using Microsoft.CSharp;

namespace WikeSoft.Core.Extension
{
    public class WikeExpressionValidate
    {
        readonly object _instance;
        readonly MethodInfo _method;

        /// <summary>
        /// 表达试运算
        /// </summary>
        /// <param name="expression">表达试</param>
        public WikeExpressionValidate(string expression)
        {
            if (expression != null && expression.IndexOf("return", StringComparison.Ordinal) < 0) expression = "return " + expression + ";";
            string className = "WikeExpression";
            string methodName = "Compute";
            CompilerParameters p = new CompilerParameters();
            p.GenerateInMemory = true;
            CompilerResults cr = new CSharpCodeProvider().CompileAssemblyFromSource(p, string.
                Format("using System;sealed class {0}{{public bool {1}(){{{2}}}}}",
                    className, methodName, expression));
            if (cr.Errors.Count > 0)
            {
                string msg = "Expression(\"" + expression + "\"): \n";
                foreach (CompilerError err in cr.Errors) msg += err.ToString() + "\n";
                throw new System.Exception(msg);
            }
            _instance = cr.CompiledAssembly.CreateInstance(className);
            if (_instance != null) _method = _instance.GetType().GetMethod(methodName);
        }

        /// <summary>
        /// 处理数据
        /// </summary>
        /// <param name="x"></param>
        /// <returns>返回计算值</returns>
        public bool Compute()
        {
            return (bool)_method.Invoke(_instance, new object[] { });
        }
    }
}
